using Microsoft.AspNetCore.Http;
using UniversalAdmin.Application.Services.Interfaces;

namespace UniversalAdmin.Application.Services.Implementations;

public class UserContextService : IUserContextService
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public UserContextService(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public Guid? GetCurrentUserId()
    {
        try
        {
            var httpContext = _httpContextAccessor.HttpContext;
            if (httpContext == null)
            {
                Console.WriteLine("HttpContext is null");
                return null;
            }

            var user = httpContext.User;
            if (user == null)
            {
                Console.WriteLine("User is null");
                return null;
            }

            if (!user.Identity?.IsAuthenticated == true)
            {
                Console.WriteLine("User is not authenticated");
                return null;
            }

            var userIdClaim = user.FindFirst("userId");
            if (userIdClaim == null)
            {
                Console.WriteLine("userId claim not found");
                // 打印所有claims用于调试
                foreach (var claim in user.Claims)
                {
                    Console.WriteLine($"Claim: {claim.Type} = {claim.Value}");
                }
                return null;
            }

            if (!Guid.TryParse(userIdClaim.Value, out var userId))
            {
                Console.WriteLine($"Failed to parse userId: {userIdClaim.Value}");
                return null;
            }

            Console.WriteLine($"Successfully got current user ID: {userId}");
            return userId;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Exception in GetCurrentUserId: {ex.Message}");
            return null;
        }
    }
} 